import React from 'react';
import { toJS } from 'mobx'
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Icon, Tools, SearchBar, List, Picker, Popover, Avatar, Flex, Modal,Tabs,Result } from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderNoData } from '../../public/BlogUtils';
import WeaUtils from '../../public/BlogUtils';
import AttentionTool from '../../public/AttentionTool';
import NewAttentionTool from '../../public/NewAttentionTool'
import HisBlogRoute from '../../hisBlog/HisBlogRoute';
import OverView from './OverView';

const getLabel = Tools.getLabel;
window.WeaUtils = WeaUtils;
const Item = Popover.Item;
const store = [
  'blogHomeStore',
  'blogAttentionStore',
]

@withRouter
@inject(...store)
@observer
export default class MyAttention extends React.Component {
  static defaultProps = {
    prefixCls: 'blog-center-attention-myAttention'
  }

  constructor(props) {
    super(props);
    this.state = {
      groupId: 'all',
      groupName: getLabel(384389, '全部关注'),
      filterVisible: 0, // 是否展示高级搜索
      visible: false,
      popover: 0, //1:查看微博总览 2：批量 0：我的关注
      path: props.parentPath + "/hisBlog/",
      userId: '',
        page:0
    }
    this.updateUserAttentionStatus = this.updateUserAttentionStatus.bind(this);
  }



  componentDidMount() {
    const { blogAttentionStore: { initalMyAttention } } = this.props;

      if(this.props.history.location.query){
          if(this.props.history.location.query.name=='special'){
              this.choseTab({},1)
          }
      }else{
          initalMyAttention();
      }
  }

  componentWillUnmount() {
    const { blogAttentionStore: { clearMyAttention } } = this.props;
   this.props.blogHomeStore.setState({hidden: false});
    clearMyAttention();
  }

    componentWillReceiveProps(nextProps){
        if(nextProps.history.location.query){
            if(nextProps.history.location.query.name=='special'){
                this.choseTab({},1)
            }
        }
    }

  onSelect=(opt,index)=>{
    let {  blogAttentionStore: { getAttentionCountInfos,isSpecial, setStoreState, MyAttentionIsSearch, initalMyAttentionList, myAttentionSelectNone } } = this.props;
    const { filterVisible } = this.state;
    if (index === 0 && filterVisible === 0&&!isSpecial) { // 查看微博总览
      setStoreState({ overviewAdValue: '', isSearch: false, overviewFlag: 0 });
      this.setState({ filterVisible: 1, visible:false, popover: 1 })
      getAttentionCountInfos();
    }else if (index === 1||isSpecial) {
      setStoreState({ showChecked: true });
      myAttentionSelectNone();
      this.setState({ visible:false });
    }else if (index === 2) { // 分组管理
      this.props.history.push({pathname:'/userCenter/blogAttention/attention/groupManagement'});
    }else if (index === 0 && filterVisible === 1) {
      setStoreState({ overviewAdValue: '', MyAttentionIsSearch: false});
      this.setState({ filterVisible: 0, visible:false, popover: 0 })
      if (MyAttentionIsSearch) initalMyAttentionList({groupId:'all'});
    }
  }

  // 我的关注--更改关注状态
  updateUserAttentionStatus(attnInfo) {
    const { blogAttentionStore: { updateUserAttentionStatus } } = this.props;
    updateUserAttentionStatus(attnInfo);
  }





  //特别关注-更新状态


  // 我的关注--分组搜索
  onPickerChange = (val,group) => {
    const { blogAttentionStore: { initalMyAttentionList, setStoreState,changeMyGroup } } = this.props;
    let groupName = val[0].split('(')[0];
    toJS(group).forEach(item=>{
      if(groupName===item.groupName) {
        changeMyGroup({groupId: item.groupId,groupName: item.groupName})
        this.setState({groupId: item.groupId,groupName: item.groupName})
        initalMyAttentionList({groupId: item.groupId})
        setStoreState({groupSearch: true})
      }
    })
  }

  // 我的关注--批量取消关注
  cancelAttention = (idSet) => {
    const { blogAttentionStore: { batchCancelAttn, initalMyAttentionList } } = this.props;
    Modal.alert(getLabel(390696, '取消关注后需要重新申请才能再次关注'),getLabel(129256, '确定要取消吗？'),
      [
        {text: getLabel(31129, '取消')},
        {text: getLabel(33703, '确认'), onPress: () => batchCancelAttn({ idSet }, () => initalMyAttentionList({ groupId: 'all' }))}
      ]
    );
  }


  //我的关注--批量取消特别关注
  batchCancelSpecial = (idSet) => {
      const { blogAttentionStore: { batchCancelSpecialUsers, initalMyAttentionList } } = this.props;
      Modal.alert(getLabel(514287,'取消特别关注后，将无法收到新微博提醒') ,getLabel(129256, '确定要取消吗？'), [
          {text: getLabel(31129, '取消')},
          {text: getLabel(33703, '确认'), onPress: () => batchCancelSpecialUsers({ 'specids':idSet })}
      ]);
  }


  // 我的关注--移动 / 复制到组 key: 1 移动 2 复制 
  onOk = (val, key, idSet) => {
    let { blogAttentionStore: { moveContactToBlogGroup, copyContactToBlogGroup, groupData, initalMyAttentionList,isSpecial }} = this.props;
    let groupName = val[0].split('(')[0];


    groupData.map(item => {
      if (groupName === item.groupName) {
        key === 1 ? 
        moveContactToBlogGroup({idSet, sourceGroup: 'all', destGroup: item.groupId},() => {
            if(isSpecial){
                initalMyAttentionList({ groupId:'special' });this.setState({groupName:item.groupName,groupId: item.groupId})
            }else{
                initalMyAttentionList({ groupId: item.groupId });this.setState({groupName:item.groupName,groupId: item.groupId})
            }
            }) :
        copyContactToBlogGroup({idSet, destGroup: item.groupId}, () => {
            if(isSpecial){
                initalMyAttentionList({ groupId:'special' });this.setState({groupName:item.groupName,groupId: item.groupId})
            }else{
                initalMyAttentionList({ groupId: item.groupId });this.setState({groupName:item.groupName,groupId: item.groupId})
            }});
      }
    });
  }


  goToUser = (userid) => {
      this.setState({ userId: userid }, () => {
          this.props.history.push(this.state.path + userid);
      });
  }

  // 我的关注--列表模板
  getTemplate = () => {
    const listStyle = 'blog-list-line';
    const ddd = this.goToUser;
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { imageUrl, lastname, departmentName, jobtitle, islower, userId, attentionStatus, isreceive, specialStatus} = data;
          return (
            <div className={listStyle}>
              <div className={`${listStyle}-userInfo`} onClick={() => {
                  ddd(userId);
              }}>
                <Avatar userId={userId} style={{width:40, height:40}} />
                <div className={`${listStyle}-userInfo-content`}>
                  <span className='lastName text-wrap'>{lastname}</span>
                  <span className='departmentName text-wrap'>{departmentName}&nbsp;{jobtitle}</span>
                </div>
              </div>
              <div className={`${listStyle}-ops`}>
                <AttentionTool 
                  isreceive={isreceive} 
                  attentionStatus={attentionStatus}
                  specialStatus={specialStatus}
                  userId={userId}
                  islower={islower}
                  callback={this.updateUserAttentionStatus}
                />
              </div>
               <NewAttentionTool
                   choseTab={this.choseTab}
                   isreceive={isreceive}
                   attentionStatus={attentionStatus}
                   specialStatus={specialStatus}
                   userId={userId}
                   islower={islower}
                   callback={this.updateUserAttentionStatus}
               />
            </div>
          )
        }
      }]
    }
    return newTemp;
  }

  /* 我的关注页面 */
  pickerContent = () => {
    const { prefixCls, blogAttentionStore: { groupData,isSpecial, MyAttentionIsSearch, myAttentionList, showChecked, myAttentionSelectAll, myAttentionSelectNone, myAttentionCancel, myAttentionLoading, groupSearch, myAttentionSearchNextPage, myAttentionSearch } } = this.props;
    let group = groupData || '', AttentionGroup = [];
    const datas = toJS(myAttentionList.data);
    const myAttentionSelectedKeys = toJS(myAttentionList.selectedRowKeys);
    const idSet = myAttentionSelectedKeys.join(',');
    const myAttentionClass = `${prefixCls}-user-list ${!MyAttentionIsSearch && showChecked && 'blog-list-checked'} ${MyAttentionIsSearch && 'blog-center-attention-myAttention-search-list'} ${MyAttentionIsSearch && showChecked && 'blog-list-checked-search'}`;
    group.forEach(item => {
      let { groupCount, groupName } = item;
      groupName = groupName + '(' + groupCount + ')';
      AttentionGroup.push({value:groupName, label:groupName});
    });
    const getBtn = (type, text) => (
        <div className={`${prefixCls}-user-btns-item`}>
            <Icon type={type} size='xs'/>
            <div>{text}</div>
        </div>
    )
    const getMoveCopy = (key, idSet) => {
      return (
        <Picker
          data={AttentionGroup}
          cols={1}
          disabled={!idSet || idSet === ''}
          onOk={val => this.onOk(val, key, idSet)}
        >
         {key === 1 ? getBtn('blog-yidong', getLabel(-81296,'移动到组')) : getBtn('blog-fuzhi', getLabel(31267,'复制到组'))} 
        </Picker>
      );
    }

    let topStyle ={"top":45};

    if(isSpecial){
        topStyle = {"top":34}
    }

    if(showChecked){
        topStyle = {"top":88}
    }
    if(showChecked&&isSpecial){
        topStyle={"top":44}
    }

    if(!isSpecial&&MyAttentionIsSearch){
        topStyle={"top":0}
    }

   const noData = ()=> {
       return isSpecial?
           <Result
           style={{"font-size": 14}}
           img={<Icon type="no-data" />}
           message={getLabel(83553, '暂无数据')}
           />:<Result
           style={{"font-size": 14}}
           img={<Icon type="no-data" />}
           message={getLabel(514295,'暂无关注人员')}
       />;
      }


    return (!myAttentionLoading && datas.length === 0 && !groupSearch) ? (
        <div>
            <div style={{"font-size": "12px", "color": "#b1b1b1","padding": "6px 6px"}}>{getLabel(515092,'提示：将关注人加入到特别关注，他发布微博时，您将收到新微博提醒，且他发布的微博将在主页中置顶显示。')}</div>
        <div className='blog-noData' style={{"margin-top": "72%"}}>
        {noData()}
        </div></div>) : (
      <div ref='myAttention' className={`${prefixCls}-user`}>
        {
          !MyAttentionIsSearch&&!isSpecial && (
            <Picker
              data={AttentionGroup}
              cols={1}
              onOk={val=>this.onPickerChange(val,group)}
            >
                <List.Item arrow='horizontal'  className={`${prefixCls}-user-title`}>{this.state.groupName}({datas && datas.length})</List.Item>
            </Picker>
          )
        }
        {
          showChecked && (
            <div className="blog-checked-top">
              <span className="blog-checked-top-cancel" onClick={myAttentionCancel}>{getLabel(201, '取消')}</span>
              <span>{getLabel(31503,"已选择")}{myAttentionSelectedKeys.length}个</span>
              {myAttentionSelectedKeys.length !== datas.length ?
                <span className="blog-checked-top-all" onClick={myAttentionSelectAll}>{getLabel(556, '全选')}</span> :
                <span className="blog-checked-top-all" onClick={myAttentionSelectNone}>{getLabel(387379,"取消全选")}</span>
              }
            </div>
          )
        }
        {isSpecial?<div style={{"font-size": "12px", "color": "#b1b1b1","padding": "6px 6px"}}>{getLabel(515092,'提示：将关注人加入到特别关注，他发布微博时，您将收到新微博提醒，且他发布的微博将在主页中置顶显示。')}</div>:""}
        <div className={myAttentionClass} style={topStyle}>
          {
            myAttentionLoading ? renderLoading : (
              <ListViewPage.Normal
                store={myAttentionList}
                getDataCustom={true}
                getTemplate={this.getTemplate}
                customHeight='100%'
                rowKey='userId'
                showCheck={showChecked}
                onEndReached={MyAttentionIsSearch ? myAttentionSearchNextPage : null}
                onRefresh={myAttentionSearch}
              />
            )
          }
          {
            showChecked && (
              <Flex className={`${prefixCls}-user-btns ${myAttentionSelectedKeys.length > 0 && 'active'}`}>
                <Flex.Item>{getMoveCopy(1, idSet)}</Flex.Item>
                <Flex.Item>{getMoveCopy(2, idSet)}</Flex.Item>
                {isSpecial?<Flex.Item  onClick={() => myAttentionSelectedKeys.length > 0 && this.batchCancelSpecial(idSet)}>{getBtn('blog-quxiaoguanzhu',getLabel(514283,'取消特别关注') )}</Flex.Item>:""}
                <Flex.Item onClick={() => myAttentionSelectedKeys.length > 0 && this.cancelAttention(idSet)}>{getBtn('blog-quxiaoguanzhu', getLabel(26938,'取消关注'))}</Flex.Item>
              </Flex>
            )
          }
        </div>
      </div>
    )
  }



  choseTab = (tab, index) => {
      let { blogAttentionStore: {changeMyGroup,initalMyAttentionList }} = this.props;


      if(index==0){
          changeMyGroup({groupId:'all'})
      this.setState({groupName: getLabel(384389, '全部关注'),page:0})
      initalMyAttentionList({groupId:'all'})
      }else{
          this.setState({page:1})
      changeMyGroup({groupId:'special'})
      initalMyAttentionList({groupId:'special'})
      }
  }
 
  render() {
    let { prefixCls, blogAttentionStore: { loading, groupData,specialCount,allCount,isSpecial, search, updateAdSearchSubject, isSearch, setStoreState, overviewAdValue, overViewSearch, overviewFlag, myAttentionSearch } } = this.props;
    let { filterVisible, visible, popover } = this.state;
    let group = groupData || '', AttentionGroup = [];
    group.forEach(item => {
      let { groupCount, groupName } = item;
      groupName = groupName + '(' + groupCount + ')';
      AttentionGroup.push({value:groupName, label:groupName});
    });

      const tabs = [
          { title: getLabel(26469, "我的关注")+'('+allCount+')' },
          { title: getLabel(514285,'特别关注') +'('+specialCount+')'}
      ];


      let popoveritems = [];

      if(filterVisible===0){
          if(isSpecial){
              popoveritems.push(<Item>{getLabel(31914,'批量操作')}</Item>);
          }else{
              popoveritems.push(<Item>{getLabel(390697,'查看微博总览')}</Item>);
              popoveritems.push(<Item>{getLabel(31914,'批量操作')}</Item>);
              popoveritems.push(<Item>{getLabel(385264,'分组管理')}</Item>);
          }

      }
      else{
          popoveritems.push(<Item>{getLabel(390698,'查看我的关注')}</Item>);
      }


    const extraBtn = [
      { 
        key: 'advanced', 
        show: filterVisible === 1 ? <Icon key='filter-o' type='filter-o' onClick={()=>this.props.history.push(search.path)} /> : '' 
      },
      { 
        key: 'drop',
        show: (
          <Popover 
            mask
            visible={visible}
            overlay={popoveritems}
            onSelect={(v,index) => this.onSelect(v,index)}
          >
            <Icon key='ellipsis' type='ellipsis' />
          </Popover>
        ),
      },
    ];
    const btnGroup = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: () => {
          search.form.resetFields();
          setStoreState({overviewAdValue: ''})
        }
      },
      { key: 'submit',
        type: 'primary',
        text: getLabel(826,"确定"),
        onClick: () => {
          setStoreState({overviewFlag: ++overviewFlag});
          overViewSearch(() => this.props.history.go(-1));
        },
      }
    ];

    if(window.location.href.indexOf('/hisBlog/')>0){
        return    <div >
            <HisBlogRoute path={this.state.path} userId={this.state.userId}/>
        </div>
    }

    return loading ? renderLoading : (

        <Tabs tabs={tabs}
              initialPage={0}
              onTabClick={this.choseTab}
              page={this.state.page}
        >
      <div >
        <SearchBar
          value={overviewAdValue}
          placeholder = {getLabel(500351,'请输入关键字')} 
          onChange={val => updateAdSearchSubject(val)}
          onSubmit={value => {
            if(popover === 0) {
              setStoreState({myAttentionLoading: true})
              myAttentionSearch(value);
              this.setState({groupId: 'all',groupName: getLabel(384389, '全部关注'),})
            } else if (popover === 1){
              setStoreState({overviewFlag: ++overviewFlag});
              overViewSearch();
            } 
          }}
          showExtraButton
          extraButton={extraBtn}
        />
        <SearchAdvanced
          store={search}
          buttonGroupData={btnGroup} 
          onChange={(condition, value) => {
            if(condition.domkey[0] === 'content') { 
              setStoreState({ overviewAdValue: value }); 
            }
          }}
        />
        { popover === 0 && this.pickerContent()}
        { popover === 1 && <OverView isSearch={isSearch}/>}
          <HisBlogRoute path={this.state.path} userId={this.state.userId}/>
      </div>
            <div >
                <SearchBar
                    value={overviewAdValue}
                    placeholder = {getLabel(500351,'请输入关键字')}
                    onChange={val => updateAdSearchSubject(val)}
                    onSubmit={value => {
                        if(popover === 0) {
                            setStoreState({myAttentionLoading: true})
                            myAttentionSearch(value);
                            this.setState({groupId: 'all',groupName: getLabel(384389, '全部关注'),})
                        } else if (popover === 1){
                            setStoreState({overviewFlag: ++overviewFlag});
                            overViewSearch();
                        }
                    }}
                    showExtraButton
                    extraButton={extraBtn}
                />
                <SearchAdvanced
                    store={search}
                    buttonGroupData={btnGroup}
                    onChange={(condition, value) => {
                        if(condition.domkey[0] === 'content') {
                            setStoreState({ overviewAdValue: value });
                        }
                    }}
                />
                { popover === 0 && this.pickerContent()}
                { popover === 1 && <OverView isSearch={isSearch}/>}
                <HisBlogRoute path={this.state.path} userId={this.state.userId}/>
            </div>


        </Tabs>

    )
  }
}